//
//  ManageGuestVC.m
//  QRMaster
//
//  Created by myApple on 15/12/7.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "ManageGuestVC.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "communityModel.h"
#import "GuestManagerTableViewCell.h"
#import "GuestModel.h"
#import "MJRefresh.h"
#import "Reachability.h"
#import "GroupGuestLogic.h"
#import "UIView+MaterialDesign.h"
#import "BulidingModel.h"
#import "FloorsModel.h"
#import "roomsModel.h"
#import "OpertionPlist.h"
#import "AppDelegate.h"
#import "GroupViewController.h"
#import "deleteGuest.h"
#import "checkPower.h"
#import "GuestLogic.h"
#import "GetNameByID.h"
#import "GuestManagerViewController.h"
#import "CustomerSearchViewController.h"
#import "BackTableViewCell.h"
#import "GuestCommunitySelectViewController.h"
#import "EditAfterAddGuestViewController.h"
#import "CommunityListInfo.h"
#import "BulidingInfoLogic.h"
#import "FloorsInfoLogic.h"
#import "RoomInfoLogic.h"
#import "ChineseString.h"
#import "pinyin.h"
#import "ZYPinYinSearch.h"
#import "BackBtn.h"
#import "StaffAndClientFirstSectionCell.h"
#import "FirstSectionModel.h"
#import "GuestLetterSort.h"
#import "AddGuestViewController.h"

@interface ManageGuestVC ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UISearchBarDelegate,UISearchDisplayDelegate>
{
    UIButton * addBtn;     //添加按钮
    UIButton * searchBtn;  //搜索按钮
    NSString * communityID;
    //    UITableView * GuestTabelView;
    NSMutableArray * GuestArray;
    NSMutableArray * groupArray;//所有组
    NSMutableArray * totalArray;//保存一份总数据，（guestarray就是搜索和不搜索状态下的都显示）
    UIButton * addNmberBtn;
    
    NSMutableArray * sectionIndexArray;//section
    NSMutableArray * rightIndexArray;//右边的index

    UILabel * footLabel;
    UILabel * titleLabel;
    UILabel * communityLabel;
    UILabel * buildingLabel;
    UILabel * floorLabel;
    UILabel * roomLabel;
    
    UISearchBar * guestSearchBar;
    UISearchDisplayController * guestDispaly;
    
    NSMutableDictionary * postDict;//请求房间里人的参数
    NSString * groupId;//组id号，查看房间
    NSString * groupName;//组名称
    
    NSString * bulidingID;
    NSString * floorID;
    NSString * roomID;
    NSString * searchContent;
    NSInteger currentPage;
    NSMutableArray * deleteGuestCell;//记住准备删除的客户cell
    
    UIView * promtView;//没有成员的提示view
    
    BOOL guestDistrPower;//客户是否有分配房间权限
    NSInteger communityMange;//在集群的角色
    AppDelegate * app;
    NSInteger totalPage;
    GetNameByID * getName;
    UIView * groupView;//组view
    QRSingleton * singleton;
    
    //多语言
    UILabel * promtNoGuestLable;
    UIButton * refreshBtn;
    
    BOOL hasCondition;//是否有过滤条件 yes 表示有过滤条件，no 表示没有过滤条件
    UIView  *deleteTitleView; //删除状态下的导航栏视图
    UILabel *deleteCountLabel;//删除记录
    
    UIImageView *allBackImgView;
    NSArray *backChooseArray;
    NSArray *backChooseImgArray;
    
    UITableView *backTableView;
    CGRect backTabelViewFrame;
    
    NSString *communityRole;
    
    
   NSString * bulidingId;
   NSString * floorId;
   NSString * roomId;
   UIImageView * switchRoomImageView;
    
//    NSMutableArray * allGroupArray;//总数据，便于搜索删除
    
    NSMutableArray * guestFisrtSectionArray;
    BOOL isUp; //是否是上拉刷新
    
}

@end

@implementation ManageGuestVC

-(id)init
{
    self = [super init];
    if (self) {
        singleton = [QRSingleton sharedQRSingleton];
        guestFisrtSectionArray = [[NSMutableArray alloc]init];
         currentPage = 1;
        guestDistrPower = NO;
        searchContent = @"";
        bulidingID = @"";
        floorID = @"";
        roomID = @"";
        postDict = [[NSMutableDictionary alloc]init];
        backChooseArray = @[NSLocalizedString(@"changeroom", nil),NSLocalizedString(@"showCommunity", nil),NSLocalizedString(@"addGuest", nil)];
        backChooseImgArray = @[@"ic_change20",@"ic_eye20",@"ic_txl"];
        GuestArray  = [[NSMutableArray alloc]init];
        groupArray = [[NSMutableArray alloc]init];
        totalArray = [[NSMutableArray alloc]init];
        deleteGuestCell = [[NSMutableArray alloc]init];
        FirstSectionModel * model = [[FirstSectionModel alloc]init];
        model.imageName = @"addClient";
        model.titleName = NSLocalizedString(@"addGuest", nil);
        [guestFisrtSectionArray addObject:model];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"guest", nil);
    
    [self prepareTabelView];
    [self switchRoomBtn];
    sectionIndexArray = [[NSMutableArray alloc]init];
    rightIndexArray = [[NSMutableArray alloc]init];
    self.view.backgroundColor = [UIColor whiteColor];
    app = [UIApplication sharedApplication].delegate;
    getName = [GetNameByID shareGetNameByID];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(GetNewGuestData:) name:@"GetNewGuestData" object:nil];//改变房间
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(failGuestData:) name:@"failGuestData" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeHeight:) name:@"height" object:nil];//改变tableview的高度
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeLanguage) name:@"changeLanguage"object:nil];
    isUp = NO;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    if (currentPage == 1) {
        [self getDataFromDisk];
    }
    if (![communityID isEqualToString:singleton.communityId] && hasCondition == YES) {
        communityID = [QRSingleton sharedQRSingleton].communityId;
        [self lookCommunityManager];
    }
    else if (![communityID isEqualToString:singleton.communityId] && hasCondition == NO)
    {
        communityID = [QRSingleton sharedQRSingleton].communityId;
        [self lookCommunityManager];
    }
    [self getName];
    switchRoomImageView.hidden = NO;
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (!groupId) {
        [guestDispaly setActive:NO animated:YES];
    }
    switchRoomImageView.hidden = YES;
}

-(void)changeLanguage
{
    promtNoGuestLable.text = NSLocalizedString(@"noGuestInfo", nil);
    [refreshBtn setTitle:NSLocalizedString(@"refreshGuest", nil) forState:0];
}

#pragma mark -- 查看当前角色
-(void)lookCommunityManager
{
    if ([self IsHaveNetwork])
    {
        [_guestTabelView.mj_header endRefreshing];
        [_guestTabelView.mj_footer endRefreshing];
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    __weak ManageGuestVC * guestSelf = self;
    power.powerBlock = ^(id data,id error)
    {
        [guestSelf stopWaiting];
        if ([data objectForKey:@"data"] != nil) {
            NSArray * CommunityArray = [[data objectForKey:@"data"] objectForKey:@"communities"];
            for (NSDictionary * dict in CommunityArray) {
                if ([[dict objectForKey:@"communityid"]isEqualToString:communityID]) {
                    communityMange = [[dict objectForKey:@"role"]integerValue];
                    if (communityMange == 5) {
                        groupId = [dict objectForKey:@"groupId"];
                        groupName = [dict objectForKey:@"groupName"];
                        [guestSelf getDataFromDisk];
                        break;
                    }
                }
            }
            if (communityID == nil) {
                communityID = [CommunityArray[0] objectForKey:@"communityid"];
            }
            if (communityMange != 3) {
                [guestSelf getGuestInfo:1];
            }
            else
            {
                promtNoGuestLable.hidden = YES;
                [self analysisFailData:NSLocalizedString(@"noManagerGuestPower", nil)];
            }
            
        }
        else if (error != nil) {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        //根据角色判断是否要显示组
        if (communityMange != 5)
        {
            if (guestFisrtSectionArray.count == 1) {
                FirstSectionModel * models = [[FirstSectionModel alloc]init];
                models.imageName = @"groupTag";
                models.titleName = NSLocalizedString(@"groupMark", nil);
                [guestFisrtSectionArray addObject:models];
                [guestSelf.guestTabelView reloadData];

            }
        }
        [_guestTabelView.mj_header endRefreshing];
        [_guestTabelView.mj_footer endRefreshing];
    };
}

-(void)prepareTabelView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = self.view.frame.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight;
    
    _guestTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height - 64) style:UITableViewStyleGrouped];
    _guestTabelView.delegate = self;
    _guestTabelView.dataSource = self;
    _guestTabelView.sectionIndexBackgroundColor = [UIColor clearColor];
    [self.view addSubview:_guestTabelView];
    
    height = 44;
    //搜索条的
    guestSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(x, y, width, height)];
    guestSearchBar.placeholder = NSLocalizedString(@"accountOrName", nil);
    guestSearchBar.layer.masksToBounds = YES;
    guestSearchBar.keyboardType = UIKeyboardTypeNamePhonePad;
    guestSearchBar.delegate = self;
    [[[guestSearchBar.subviews objectAtIndex:0].subviews objectAtIndex:0]removeFromSuperview];
    guestSearchBar.backgroundColor = UIColorFromRGB(0xebebeb);
    guestDispaly = [[UISearchDisplayController alloc]initWithSearchBar:guestSearchBar contentsController:self];
    guestDispaly.searchResultsDataSource = self;
    guestDispaly.searchResultsDelegate = self;
    guestDispaly.delegate = self;
    self.edgesForExtendedLayout = UIRectEdgeTop;
    self.extendedLayoutIncludesOpaqueBars = NO;
//    guestSearchBar.barTintColor = UIColorFromRGB(0xebebeb);
    
    y = 0;
    height = 48;
    UIView * footView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    
    y = 15;
    height = 18;
    footLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    footLabel.textColor = UIColorFromRGB(0x333333);
    footLabel.font = [UIFont systemFontOfSize:12.0];
    footLabel.textAlignment = NSTextAlignmentCenter;
    [footView addSubview:footLabel];
    _guestTabelView.tableFooterView = footLabel;
    _guestTabelView.backgroundColor = UIColorFromRGB(0xebebeb);
    [_guestTabelView.mj_header beginRefreshing];
    _guestTabelView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^
    {
        currentPage = 1;
        [self lookCommunityManager];
    }];
     _guestTabelView.tableHeaderView = guestSearchBar;
    _guestTabelView.mj_footer=[MJRefreshBackGifFooter footerWithRefreshingBlock:^
    {
        if (currentPage < totalPage || GuestArray.count >= 8) {
            isUp = YES;
            //currentPage += 1;
            [self getGuestInfo:(int)(currentPage + 1)];
        }
        else
        {
            [PromptInfoView showMessage:NSLocalizedString(@"noMoreGuestInfo", nil)];
            [_guestTabelView.mj_footer endRefreshing];
            [_guestTabelView.mj_header endRefreshing];
        }


    }];
    
    promtView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    promtView.backgroundColor = self.view.backgroundColor;
    promtView.hidden = YES;
    [self.view addSubview:promtView];
    
    //房间没有客户
    promtNoGuestLable = [[UILabel alloc]init];
    promtNoGuestLable.hidden = YES;
    promtNoGuestLable.frame = CGRectMake(0, (ScreenHeight-64-49) / 2.0 , ScreenWidth, 20);
    promtNoGuestLable.text = NSLocalizedString(@"noGuestInfo", nil);
    promtNoGuestLable.textColor = RGBA(211, 211, 211, 1);
    promtNoGuestLable.textAlignment = NSTextAlignmentCenter;
    promtNoGuestLable.font = [UIFont systemFontOfSize:14.0];
    [promtView addSubview:promtNoGuestLable];
    
    x = 0;
    width = ScreenWidth;
    height = 40;
    y = (ScreenHeight-64-49) / 2.0 - 50;
    refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    refreshBtn.frame = CGRectMake(x, y, width, height);
    [refreshBtn setTitle:NSLocalizedString(@"refreshGuest", nil) forState:0];
    [refreshBtn setTitleColor:RGBA(125, 194, 52, 1) forState:0];
    refreshBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [refreshBtn addTarget:self action:@selector(refreshGuest) forControlEvents:UIControlEventTouchUpInside];
    [promtView addSubview:refreshBtn];
}

#pragma mark ----------searchbar代理
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    if (!groupId) {
        CustomerSearchViewController *customerSearch=[[CustomerSearchViewController alloc]initWIthCommunityId:communityID];
        [self.navigationController pushViewController:customerSearch animated:YES];
    }
    else
    {
        [searchBar setShowsCancelButton:YES];
        for(id cc in [searchBar.subviews[0] subviews])
        {
            if([cc isKindOfClass:[UIButton class]])
            {
                UIButton *btn = (UIButton *)cc;
                [btn setTitle:NSLocalizedString(@"alterCancel", nil) forState:UIControlStateNormal];
            }
        }
    }
    
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    for (UIView * subView in guestDispaly.searchResultsTableView.subviews)
    {
        if ([subView isKindOfClass:[UILabel class]]) {
            UILabel * label = (UILabel *)subView;
            label.text = NSLocalizedString(@"noSearch", nil);
        }
    }
    return YES;
}



-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self managerSearch];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchContent = @"";
    sectionIndexArray = [GuestLetterSort letterSortArray:totalArray];
    rightIndexArray = [GuestLetterSort indexArray:totalArray];
    [_guestTabelView reloadData];
}

-(void)switchRoomBtn
{
    switchRoomImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 100, 2, 84, 40)];
    switchRoomImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer * changeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeCommunity)];
    [switchRoomImageView addGestureRecognizer:changeTap];
    [self.navigationController.navigationBar addSubview:switchRoomImageView];
    
    UILabel * switchRoomLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 84, 20)];
    switchRoomLabel.text = NSLocalizedString(@"changeroom", nil);
    switchRoomLabel.textColor = UIColorFromRGBAndA(0x7dc234, 1);
    switchRoomLabel.font = [UIFont systemFontOfSize:15.0];
    switchRoomLabel.textAlignment = NSTextAlignmentRight;
    [switchRoomImageView addSubview:switchRoomLabel];
}


#pragma mark-------------------点击所有组
-(void)clickGroup
{
    GroupViewController * gvc = [[GroupViewController alloc]init];
    gvc.communityId = communityID;
    gvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:gvc animated:YES];
}


-(void)changeHeight:(NSNotification *)not
{
    CGFloat height = [[not.userInfo objectForKey:@"height"]floatValue];
    _guestTabelView.frame = CGRectMake(0, 0, self.view.frame.size.width,[UIScreen mainScreen].bounds.size.height - 49 - height);
}

#pragma mark  点击刷新tableview
-(void)refreshGuest
{
    [self lookCommunityManager];
}


#pragma mark ==== 点击删除传过来的信息
-(void)makeSureDelete
{
    NSString * deleteString = [deleteGuest deleteGuest:deleteGuestCell inAllGuestArray:GuestArray];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDicts = [[NSMutableDictionary alloc]init];
    NSString * urlString = @"";
    [postDicts setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDicts setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDicts setValue:communityID forKey:@"communityId"];
    if (groupId) {
        urlString = DELETEGROUPCLIENT;
        [postDicts setValue: groupId forKey:@"groupId"];
        [postDicts setValue: deleteString forKey:@"clientId"];
        if([self getTimestamp:groupId] != nil)
        {
            [postDict setValue:[self getTimestamp:groupId] forKey:@"timestamp"];
        }
        else
        {
            [postDict setValue:@"" forKey:@"timestamp"];
        }
    }
    else
    {
        urlString = DELETEGUEST;
        [postDicts setValue:deleteString forKey:@"memberIds"];
        if([self getTimestamp:communityID timeKey:@"customer_timestamp"] != nil)
        {
            [postDicts setValue:[self getTimestamp:communityID timeKey:@"customer_timestamp"] forKey:@"timestamp"];
        }
        else
        {
            [postDicts setValue:@"" forKey:@"timestamp"];
        }
    }
    __weak ManageGuestVC * guestSelf = self;
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(urlString) params:postDicts block:^(id downLoadData, id error)
     {
         if ([downLoadData objectForKey:@"cache"] != nil) {
             if([@"1" isEqualToString:[NSString stringWithFormat:@"%@",[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]]]==YES)
             {
                 [_guestTabelView reloadData];
                 currentPage = 1;
                 [self getGuestInfo:1];
             }
             else
             {
                 if (groupId) {
                     [self updateTimestamp:groupId timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                     GroupGuestLogic * groupLogic = [[GroupGuestLogic alloc]init];
                     [groupLogic deleteGroupGuestInfoByGroupId:groupId];
                 }
                 else
                 {
                     [self updateTimestamp:communityID timeKey:@"customer_timestamp" timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                     GuestLogic * guestLogic = [[GuestLogic alloc]init];
                     [guestLogic deleteGuestInfo:deleteString withCommunityId:communityID];
                 }
                 
                 if ([downLoadData objectForKey:@"data"] != nil)
                 {
                     [self getDataFromDisk];
                     [_guestTabelView reloadData];
                     currentPage = 1;
                     [self getGuestInfo:1];
                 }
                 
             }
             
         }
         else
         {
              [PromptInfoView showMessage:[error objectForKey:@"info"]];
             if ([[error objectForKey:@"status"]integerValue] == 334)
             {
                 currentPage = 1;
                 [guestSelf getGuestInfo:1];//用户在别处被删除了
             }

         }
     }];
    
}


#pragma mark === 通知过来说改变了房间，所以要重新请求数据
-(void)GetNewGuestData:(NSNotification *)not
{
    communityID = [not.userInfo objectForKey:@"communityId"];
    bulidingID = [not.userInfo objectForKey:@"buildingId"];
    floorID = [not.userInfo objectForKey:@"floorId"];
    roomID = [not.userInfo objectForKey:@"roomId"];
    [GuestArray removeAllObjects];
    [self lookCommunityManager];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView != _guestTabelView) {
        return sectionIndexArray.count;
    }
    return sectionIndexArray.count + 1;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return rightIndexArray;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"";
    }
    return rightIndexArray[section - 1];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return guestFisrtSectionArray.count;
    }
    else
    {
        NSArray * rowCount = sectionIndexArray[section - 1];
        return rowCount.count;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.1;
    }
    return 34.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (tableView != _guestTabelView) {
//        NSString * string = @"resultCell";
//        GuestManagerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
//        if (!cell) {
//            cell = [[GuestManagerTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
//        }
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        NSArray * rowArray = sectionIndexArray[indexPath.section];
//        GuestModel * model = rowArray[indexPath.row];
//        cell.guestName = model.guestName;
//        cell.headUrl = model.headUrl;
//        return cell;
//    }
    if (indexPath.section == 0) {
        NSString * identity = @"cellId";
        StaffAndClientFirstSectionCell * cell = [tableView dequeueReusableCellWithIdentifier:identity];
        if (!cell) {
            cell = [[StaffAndClientFirstSectionCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identity];
        }
        FirstSectionModel * model = guestFisrtSectionArray[indexPath.row];
        cell.imageNameString = model.imageName;
        cell.titleString = model.titleName;
        return cell;
    }else
    {
        NSString * string = @"cell";
        GuestManagerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (!cell) {
            cell = [[GuestManagerTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSArray * rowArray = sectionIndexArray[indexPath.section - 1];
        GuestModel * model = rowArray[indexPath.row];
        cell.guestName = model.guestName;
        cell.headUrl = model.headUrl;
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                [self addMenber];
                break;
            case 1:
                [self clickGroup];
                break;
            default:
                break;
        }
    }
    else
    {
        GuestManagerViewController * gmvc = [[GuestManagerViewController alloc]init];
        NSArray * array = sectionIndexArray[indexPath.section - 1];
        if (array.count > indexPath.row) {
            gmvc.model = array[indexPath.row];
            gmvc.communityid = communityID;
            gmvc.comeFrom = NO;
            gmvc.communityRole = [NSString stringWithFormat:@"%ld",(long)communityMange];
            gmvc.groupId = groupId;
            gmvc.groupName = groupName;
            gmvc.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:gmvc animated:YES];
        }
    }
    
}

#pragma mark --添加职员或者客户
-(void)addMenber
{
    //先请求一下当前集群的角色 防止同步操作
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    power.powerBlock = ^(id data,id error)
    {
        if ([data objectForKey:@"data"]!= nil) {
            NSArray * CommunityData = [[data objectForKey:@"data"] objectForKey:@"communities"];
            for (NSDictionary * dict in CommunityData) {
                if ([communityID isEqualToString:[dict objectForKey:@"communityid"]]) {
                    communityRole = [dict objectForKey:@"role"];
                    groupId = [dict objectForKey:@"groupId"];
                    break;
                }
            }
            if ([communityRole isEqualToString:@"1"]||[communityRole isEqualToString:@"2"]||[communityRole isEqualToString:@"5"]) {

//                EditAfterAddGuestViewController * gmvc = [[EditAfterAddGuestViewController alloc]init];
//                gmvc.communityId = communityID;
//                gmvc.communityRole = communityRole;
//                gmvc.groupId = groupId;
//                gmvc.groupName = groupName;
//                gmvc.hidesBottomBarWhenPushed = YES ;
//                [self.navigationController pushViewController:gmvc animated:YES];
                
                AddGuestViewController * agvc = [[AddGuestViewController alloc] init];
                agvc.communityId = communityID;
                agvc.communityRole = communityRole;
                agvc.groupId = groupId;
                agvc.groupName = groupName;
                agvc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:agvc animated:YES];
            }
            else
            {
                [PromptInfoView showMessage:NSLocalizedString(@"noPowerToAdd", nil)];
                
            }
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        
    };
}

#pragma mark ---------切换集群
-(void)changeCommunity
{
    GuestCommunitySelectViewController * gcsvc = [[GuestCommunitySelectViewController alloc]initWith:communityID withBulidingId:bulidingID withFloorId:floorID withRoomId:roomID];
    gcsvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:gcsvc animated:YES];
    gcsvc.HouseInfo = ^(NSString * communityid,NSString * bulidingid,NSString * floorid,NSString * roomid)
    {
        bulidingID = bulidingid;
        floorID = floorid;
        roomID = roomid;
        getName.bulidingId = bulidingid;
        getName.floorId = floorid;
        getName.roomId = roomid;
        [QRSingleton sharedQRSingleton].roomId = roomid;
        if (![bulidingID isEqualToString:@""]) {
            hasCondition = YES;
        }
        //切换集群有多个地方，所有切换集群的一起处理，切换房间的一起处理
        if ([communityID isEqualToString:singleton.communityId] && (![bulidingID isEqualToString:@""] ||[bulidingID isEqualToString:@""]))
        {
            [self getGuestInfo:1];
            currentPage = 1;
        }
        communityLabel.text = [NSString stringWithFormat:@"%@ %@",communityLabel.text,[getName GetBulidingNameByID:bulidingid GetFloorName:floorid GetRoomName:roomid]];
    };
}

-(void)houseMenuDatasendFailManage:(NSString *)string
{
    [self analysisFailData:string];
}

//查询客户人数
-(void)getGuestInfo:(int )CurrentPage
{
    hasCondition = NO;//判断是否有筛选条件，如楼栋，楼层，房间，搜索条件
    if ([self IsHaveNetwork]) {
        [_guestTabelView.mj_header endRefreshing];
        [_guestTabelView.mj_footer endRefreshing];
        return;
    }
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    [postDict setValue:communityID forKey:@"communityId"];
    [postDict setValue:bulidingID forKey:@"buildingId"];
    [postDict setValue:floorID forKey:@"floorId"];
    [postDict setValue:roomID forKey:@"roomId"];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[NSString stringWithFormat:@"%d",CurrentPage] forKey:@"currentPage"];
    [postDict setValue:@"8" forKey:@"size"];
    [postDict setValue:searchContent forKey:@"search"];
    if (communityMange == 5) {
        [postDict setValue:@"0" forKey:@"withoutGroup"];
    }
    else
    {
        [postDict setValue:@"1" forKey:@"withoutGroup"];
    }
    
    if([self getTimestamp:communityID timeKey:@"customer_timestamp"] != nil)
    {
        [postDict setValue:[self getTimestamp:communityID timeKey:@"customer_timestamp"] forKey:@"timestamp"];
         [postDict setValue:@"" forKey:@"timestamp"];
    }
    else
    {
        [postDict setValue:@"" forKey:@"timestamp"];
    }
    
    if (![bulidingID isEqualToString:@""]) {
        hasCondition = YES;
    }
    
    if (floorID != nil && [@"" isEqualToString:floorID] == NO)
    {
        hasCondition = YES;
    }
    if (roomID != nil && [@"" isEqualToString:roomID] == NO)
    {
        hasCondition = YES;
    }
    if (searchContent != nil && [@"" isEqualToString:searchContent] == NO)
    {
        hasCondition = YES;
    }
//    if (hasCondition == NO && CurrentPage == 1)
//    {
//        [self getDataFromDisk];
//        [_guestTabelView reloadData];
//    }
    if (isUp == YES) {
        hasCondition = YES;
    }
    
    [self startWaiting:nil color:nil addToView:self.view];
    __weak ManageGuestVC * groupSelf = self;
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(GETGUESTINFO) params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         [_guestTabelView.mj_header endRefreshing];
         [_guestTabelView.mj_footer endRefreshing];
         isUp = NO;
         if (hasCondition == NO)
         {
             if ([downLoadData objectForKey:@"cache"] != nil)
             {
                 [self updateTimestamp:communityID timeKey:@"customer_timestamp" timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                 if([@"1" isEqualToString:[NSString stringWithFormat:@"%@",[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]]]==YES )
                 {
                     promtView.hidden = YES;
                     _guestTabelView.hidden = NO;
                     
                     if ([downLoadData objectForKey:@"data"] != nil)
                     {
                         [self analysisSuccessData:downLoadData];
                     }
                 }
             }
             else if(error != nil)
             {
                 if([[error objectForKey:@"status"]longValue] == 301 && communityMange == 3)
                 {
                     promtNoGuestLable.hidden = NO;
//                     _guestTabelView.hidden = YES;
                     [sectionIndexArray removeAllObjects];
                     [rightIndexArray removeAllObjects];
                     footLabel.text = NSLocalizedString(@"noGuestInfo", nil);
                     [_guestTabelView reloadData];
                     
                 }
                 [groupSelf analysisFailData:[error objectForKey:@"info"]];
             }
        }
         else
         {
             promtView.hidden = YES;
             _guestTabelView.hidden = NO;
             
             if ([downLoadData objectForKey:@"data"] != nil)
             {
                  [self analysisSuccessData:downLoadData];
             }
             else
             {
                 if([[error objectForKey:@"status"]longValue] == 301 || communityMange == 3)
                 {
                     promtNoGuestLable.hidden = NO;
//                     _guestTabelView.hidden = YES;
                     [sectionIndexArray removeAllObjects];
                     [rightIndexArray removeAllObjects];
                      footLabel.text = NSLocalizedString(@"noGuestInfo", nil);
                     [_guestTabelView reloadData];
                 }
                 if (currentPage == 1) {
                     [GuestArray removeAllObjects];
                     [_guestTabelView reloadData];
                 }
                 else
                 {
                     [_guestTabelView reloadData];
                 }
                 [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
             }
         }
     }
     ];


}

-(void)analysisSuccessData:(id)downLoadData
{
    promtView.hidden = YES;
    _guestTabelView.hidden = NO;
    NSDictionary * totalInfo = [[downLoadData objectForKey:@"data"] objectForKey:@"page"];
    totalPage = [[totalInfo objectForKey:@"total"]integerValue];
    currentPage = [[totalInfo objectForKey:@"currentpage"]integerValue];
    //下拉刷新才要remove
    if (currentPage == 1) {
        [GuestArray removeAllObjects];
        [groupArray removeAllObjects];
    }
    NSMutableArray * guestInfo = [[downLoadData objectForKey:@"data"] objectForKey:@"customers"];
    for (NSDictionary * guestDict in guestInfo) {
        GuestModel * model = [[GuestModel alloc]init];
        model.guestid = [NSString stringWithFormat:@"%@",[guestDict objectForKey:@"id"]];
        model.guestName = [guestDict objectForKey:@"name"];
        model.sex = [NSString stringWithFormat:@"%@",[guestDict objectForKey:@"gender"]];
        model.headUrl = [guestDict objectForKey:@"headurl"];
        model.telePhone = [NSString stringWithFormat:@"%@",[guestDict objectForKey:@"mobile"]];
        model.email = [guestDict objectForKey:@"email"];
        model.certificaties = [guestDict objectForKey:@"identityid"];
        model.firstChar = [NSString stringWithFormat:@"%@",[guestDict objectForKey:@"firstChar"]];
        model.areaCode = [guestDict objectForKey:@"areaCode"];
        [GuestArray addObject:model];
    }
    
    for(int i = 0; i<GuestArray.count; i++)
    {
        ((GuestModel*)[GuestArray objectAtIndex:i]).firstChar=[self FirstCharToStr:((GuestModel *)[GuestArray objectAtIndex:i]).firstChar];
    }
    
    //首字母处理
    for(int i = 0; i<GuestArray.count; i++)
    {
        for(int j = i; j<GuestArray.count; j++)
        {
            if([((GuestModel *)[GuestArray objectAtIndex:i]).firstChar isEqualToString:((GuestModel *)[GuestArray objectAtIndex:j]).firstChar ]==YES &&j!=i)
            {
                GuestModel * model = [[GuestModel alloc]init];
                model=[GuestArray objectAtIndex:j];
                model.firstChar=@"";
            }
        }
    }
     totalArray = [GuestArray mutableCopy];
    sectionIndexArray = [GuestLetterSort letterSortArray:GuestArray];
    rightIndexArray = [GuestLetterSort indexArray:GuestArray];
    if (totalArray.count == 0 || totalArray.count == 1) {
        footLabel.text = [NSString stringWithFormat:@"%@ %lu %@",NSLocalizedString(@"total", nil),(unsigned long)totalArray.count,NSLocalizedString(@"guest", nil)];
    }
    else
    {
        footLabel.text = [NSString stringWithFormat:@"%@ %lu %@",NSLocalizedString(@"total", nil),(unsigned long)totalArray.count,NSLocalizedString(@"guests", nil)];
    }
    [_guestTabelView reloadData];
   
    if (currentPage == 1 && hasCondition == NO) {
        if (groupId) {
             GroupGuestLogic * groupLogic = [[GroupGuestLogic alloc]init];
            [groupLogic deleteGroupGuestInfoByGroupId:groupId];
            for (int i=0; i<GuestArray.count; i++)
            {
                GuestModel * model = [[GuestModel alloc]init];
                model=[GuestArray objectAtIndex:i];
                [groupLogic insertGroupGuestInfo:model groupName:nil groupStartTime:nil  groupEndTime:nil groupId:groupId];
            }
        }
        else
        {
            //数据有更新，需先清除表中数据，再进行插入
            GuestLogic *guestLogic = [[GuestLogic alloc]init];
            [guestLogic deleteGuestInfo:communityID];
            for (int i=0; i<GuestArray.count; i++) {
                GuestModel * model = [[GuestModel alloc]init];
                model=[GuestArray objectAtIndex:i];
                [guestLogic insertStaffData:model withCommuntiyId:[[NSUserDefaults standardUserDefaults] objectForKey:@"communityId"]];
            }
        }
    }
}


//编辑或者添加客户刷新列表
-(void)getGuestInfo
{
    [self getGuestInfo:1];
    
}

//请求时，错误的返回,或者没有管理权限
-(void)analysisFailData:(NSString *)str
{
    [PromptInfoView showMessage:str superView:self.view];
    //    [GuestArray removeAllObjects];
    [_guestTabelView.mj_header endRefreshing];
    [_guestTabelView.mj_footer endRefreshing];

    if (currentPage == 1) {
        [GuestArray removeAllObjects];
        [_guestTabelView reloadData];
    }
    else
    {
        [_guestTabelView reloadData];
    }
    
    if (groupId)
    {
        GroupGuestLogic * groupLogic = [[GroupGuestLogic alloc]init];
        [groupLogic deleteGroupGuestInfoByGroupId:groupId];
      
    }
    else
    {
        //数据有更新，需先清除表中数据，再进行插入
        GuestLogic *guestLogic = [[GuestLogic alloc]init];
        [guestLogic deleteGuestInfo:communityID];
    }

}

#pragma mark --获取房间时，此用户在此集群没有权限
-(void)failGuestData:(NSNotification *)not
{
    NSString * nowCommunity = [not.userInfo objectForKey:@"community"];
    communityID = nowCommunity;
    [self analysisFailData:NSLocalizedString(@"noManagerGuestPower", nil)];
    
}

#pragma mark -- 搜索结果处理
-(void)managerSearch
{
    if ([self IsHaveNetwork]) {
//        [_guestTabelView.mj_header endRefreshing];
//        [_guestTabelView.mj_footer endRefreshing];
        return;
    }
    
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    [postDict setValue:communityID forKey:@"communityId"];
    [postDict setValue:bulidingID forKey:@"buildingId"];
    [postDict setValue:floorID forKey:@"floorId"];
    [postDict setValue:roomID forKey:@"roomId"];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[NSString stringWithFormat:@"%d",1] forKey:@"currentPage"];
    [postDict setValue:@"8" forKey:@"size"];
    [postDict setValue:guestSearchBar.text forKey:@"search"];
    searchContent = guestSearchBar.text;
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    __weak ManageGuestVC * guestSelf = self;
    [rnw initWithPath:POST(GETGUESTINFO) params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
//         [_guestTabelView.mj_header endRefreshing];
//         [_guestTabelView.mj_footer endRefreshing];
         if ([downLoadData objectForKey:@"data"]) {
             NSArray * guestInfo = [[downLoadData objectForKey:@"data"] objectForKey:@"customers"];
             if (guestInfo.count == 0 ) {
                 [PromptInfoView showMessage:NSLocalizedString(@"noGuestInfo", nil) superView:guestSelf.view];
             }
             [GuestArray removeAllObjects];
             for (NSDictionary * guestDict in guestInfo) {
                 GuestModel * model = [[GuestModel alloc]init];
                 model.guestid = [guestDict objectForKey:@"id"];
                 model.guestName = [guestDict objectForKey:@"name"];
                 model.sex = [guestDict objectForKey:@"gender"];
                 model.headUrl = [guestDict objectForKey:@"headurl"];
                 model.telePhone = [guestDict objectForKey:@"mobile"];
                 model.email = [guestDict objectForKey:@"email"];
                 model.certificaties = [guestDict objectForKey:@"identityid"];
                 model.firstChar = [guestDict objectForKey:@"firstChar"];
                 model.areaCode = [guestDict objectForKey:@"areaCode"];
                 [GuestArray addObject:model];
             }
             GuestArray = [GuestLetterSort getChinesArray:GuestArray];
             sectionIndexArray = [GuestLetterSort letterSortArray:GuestArray];
             rightIndexArray = [GuestLetterSort indexArray:GuestArray];
             [guestDispaly.searchResultsTableView reloadData];
             for(int i = 0; i<GuestArray.count; i++)
             {
                 ((GuestModel*)[GuestArray objectAtIndex:i]).firstChar=[self FirstCharToStr:((GuestModel *)[GuestArray objectAtIndex:i]).firstChar];
             }
             
             //首字母处理
             for(int i = 0; i<GuestArray.count; i++)
             {
                 for(int j = i; j<GuestArray.count; j++)
                 {
                     if([((GuestModel *)[GuestArray objectAtIndex:i]).firstChar isEqualToString:((GuestModel *)[GuestArray objectAtIndex:j]).firstChar ]==YES &&j!=i)
                     {
                         GuestModel * model = [[GuestModel alloc]init];
                         model=[GuestArray objectAtIndex:j];
                         model.firstChar=@"";
                     }
                 }
             }

//             [_guestTabelView reloadData];
         }
         else
         {
             [guestSelf analysisFailData:[error objectForKey:@"info"]];
             if ([[error objectForKey:@"status"] integerValue] == 301) {
                 [sectionIndexArray removeAllObjects];
                 [rightIndexArray removeAllObjects];
                 [guestDispaly.searchResultsTableView reloadData];
                 [guestSelf.guestTabelView reloadData];
             }
             
         }
     }
     ];

}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"cancelGuestSearch" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

# pragma 读取本地数据
-(void)getDataFromDisk
{
    hasCondition = NO;
    
    //国际版做了加nil修改
    if (![bulidingID isEqualToString:@""] && bulidingID != nil) {
        hasCondition = YES;
    }
    
    if (floorID != nil && [@"" isEqualToString:floorID] == NO) {
        hasCondition = YES;
    }
    if (roomID != nil && [@"" isEqualToString:roomID] == NO) {
        hasCondition = YES;
    }
    if (searchContent != nil && [@"" isEqualToString:searchContent] == NO) {
        hasCondition = YES;
    }
    if(hasCondition == YES)
    {
        return;
    }
    
    if (groupId)
    {
        [GuestArray removeAllObjects];
        GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
        [groupGuestLogic queryGroupGuestInfo:groupId block:^(NSMutableArray *groupGuestArray)
         {
             for (NSDictionary * guestDict in groupGuestArray) {
                 GuestModel * model = [[GuestModel alloc]init];
                 model.guestid = [NSString stringWithFormat:@"%@",[guestDict objectForKey:@"id"]];
                 model.guestName = [guestDict objectForKey:@"name"];
                 model.sex = [NSString stringWithFormat:@"%@",[guestDict objectForKey:@"gender"]];
                 model.headUrl = [guestDict objectForKey:@"headurl"];
                 model.telePhone = [NSString stringWithFormat:@"%@",[guestDict objectForKey:@"mobile"]];
                 model.email = [guestDict objectForKey:@"email"];
                 model.certificaties = [guestDict objectForKey:@"identityid"];
                 model.firstChar = [NSString stringWithFormat:@"%@",[guestDict objectForKey:@"firschar"]];
                 model.areaCode = [guestDict objectForKey:@"areaCode"];
                 [GuestArray addObject:model];
             }
         }
         ];
    }
    else
    {
        GuestLogic *guestLogic = [[GuestLogic alloc]init];
        [guestLogic queryGuestInfo:[[NSUserDefaults standardUserDefaults] objectForKey:@"communityId"] block:^(NSMutableArray *arr)
         {
             GuestArray = arr;
         }
         ];
    }
    GuestArray = [NSMutableArray arrayWithArray:[GuestLetterSort getChinesArray:GuestArray]];
    sectionIndexArray = [GuestLetterSort letterSortArray:GuestArray];
    rightIndexArray = [GuestLetterSort indexArray:GuestArray];
    
    //首字母处理
    for(int i = 0; i<GuestArray.count; i++)
    {
        for(int j = i; j<GuestArray.count; j++)
        {
            if([((GuestModel *)[GuestArray objectAtIndex:i]).firstChar isEqualToString:((GuestModel *)[GuestArray objectAtIndex:j]).firstChar ]==YES &&j!=i)
            {
                GuestModel * model = [[GuestModel alloc]init];
                model=[GuestArray objectAtIndex:j];
                model.firstChar=@"";
            }
        }
    }
    totalArray = [GuestArray mutableCopy];
    if (totalArray.count == 0 || totalArray.count == 1) {
        footLabel.text = [NSString stringWithFormat:@"%@ %lu %@",NSLocalizedString(@"total", nil),(unsigned long)totalArray.count,NSLocalizedString(@"guest", nil)];
    }
    else
    {
        footLabel.text = [NSString stringWithFormat:@"%@ %lu %@",NSLocalizedString(@"total", nil),(unsigned long)totalArray.count,NSLocalizedString(@"guests", nil)];
    }
    [_guestTabelView reloadData];
}

-(void)showVc:(NSInteger)index
{
    if (index == 1) {
        [self viewWillAppear:YES];
    }
}

#pragma mark -------获取集群，楼栋，楼层，房间 名称
-(void)getName
{
    if (bulidingID != nil && [@"" isEqualToString:bulidingID] == NO)
    {
        BulidingInfoLogic *buildingInfoLogic = [[BulidingInfoLogic alloc]init];
        [buildingInfoLogic queryBulidingName:bulidingID block:^(NSString *bulidingName)
        {
            [QRSingleton sharedQRSingleton].buildingName = bulidingName;
        }
         ];
    }
    else
    {
        [QRSingleton sharedQRSingleton].buildingName = @"";
    }
    if (floorID != nil && [@"" isEqualToString:floorID] == NO)
    {
        FloorsInfoLogic *floorInfoLogic = [[FloorsInfoLogic alloc]init];
       [floorInfoLogic queryfloorName:floorID block:^(NSString *floorName)
       {
           [QRSingleton sharedQRSingleton].floorName = floorName;
       }
        ];
    }
    else
    {
        [QRSingleton sharedQRSingleton].floorName = @"";
    }
    if (roomID != nil && [@"" isEqualToString:roomID] == NO)
    {
        RoomInfoLogic *roomInfoLogic = [[RoomInfoLogic alloc]init];
        [roomInfoLogic queryRoomName:roomID block:^(NSString *roomName)
        {
            [QRSingleton sharedQRSingleton].roomName = roomName;
        }
         ];
    }
    else
    {
        [QRSingleton sharedQRSingleton].roomName = @"";
    }
}

-(void)hiddenVc:(NSInteger)index
{
    if (index == 1) {
        [self viewWillDisappear:YES];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

//通过groupId来查询到时间戳
-(NSString *)getTimestamp:(NSString *)_groupId
{
    GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
    return [groupGuestLogic queryGroupGuestTime:_groupId];
}


//通过groupId来更新时间戳
-(void)updateTimestamp:(NSString *)_groupId timeKeyValue:(NSString *)timeKeyValue
{
    GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
    [groupGuestLogic updateGroupGuestTime:_groupId keyValue:timeKeyValue];
}





@end
